package com.soup.dao;

import com.soup.domain.Person;
import com.soup.utils.JdbcTemplate;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PersonDao {

    private JdbcTemplate jdbcTemplate;
    public PersonDao(){
        jdbcTemplate = JdbcTemplate.getJdbcTemplate();
    }

    public List<Person> query(Map<String,Object> condition) {
        StringBuffer sql = new StringBuffer("select * from person where 1=1");
        List<Object> objects = new ArrayList<Object>();
        condition.forEach((key,value)->{
            sql.append(" and "+key+"=?");
            objects.add(value);
        });
        System.out.println(sql);
        List<Person> query = null;
        try {
            query = jdbcTemplate.query(sql.toString(), Person.class,objects.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public List<Person> findByName(String name) {
        String sql = "select * from person where name like ?";
        List<Person> query = null;
        try {
            query = jdbcTemplate.query(sql, Person.class,name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public int addPerson(Person person){
        String sql = "insert into person values(?,?,?,?,?,?)";
        try {
            return jdbcTemplate.modify(sql,person.getId(),
                    person.getName(),
                    person.getPassword(),
                    person.getInd(),
                    person.getState(),
                    person.getMoney());
        } catch (SQLException e) {
            return -1;
        }
    }

    public int delete(String id){
        String sql = "delete from person where id=?";
        try {
            return jdbcTemplate.modify(sql,id);
        } catch (SQLException e) {
            return -1;
        }
    }

    public int update(Person person){
        String sql = "update person set name=?,password=?,state=?,money=? where id=?";
        try {
            return jdbcTemplate.modify(sql,person.getName(),
                    person.getPassword(),
                    person.getState(),
                    person.getMoney(),
                    person.getId());
        } catch (SQLException e) {
            return -1;
        }
    }
}
